package com.xgst.land.base

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import androidx.lifecycle.ViewModel
import com.blankj.utilcode.util.ToastUtils
import com.hjq.http.EasyHttp
import com.hjq.http.config.IRequestApi
import com.hjq.http.listener.OnHttpListener
import com.xgst.land.utils.ProgressUtils
import java.lang.Exception

open abstract class BaseViewModel:ViewModel(), LifecycleOwner {
     private val mLifecycle: LifecycleRegistry = LifecycleRegistry(this)

     init {
          mLifecycle.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
          mLifecycle.handleLifecycleEvent(Lifecycle.Event.ON_RESUME)
     }

     fun <T> httpPost(api:IRequestApi,OnCallBack:(T)->Unit){
          showProgress()
          EasyHttp.post(this)
               .api(api)
               .request(object : OnHttpListener<T>{
                    override fun onSucceed(result: T) {
                        dismissProgress()
                         OnCallBack(result)
                    }

                    override fun onFail(e: Exception) {
                         dismissProgress(e.message?:"请求错误")
                    }
               })
     }

     fun <T> httpGet(api:IRequestApi,OnCallBack:(T)->Unit){
          showProgress()
          EasyHttp.get(this)
               .api(api)
               .request(object : OnHttpListener<T>{
                    override fun onSucceed(result: T) {
                         dismissProgress()

                    }

                    override fun onFail(e: Exception) {
                         dismissProgress(e.message?:"请求错误")
                    }
               })
     }

     fun dismissProgress(toastMessage:String = ""){
          ProgressUtils.dismiss()
          if(toastMessage.isNotEmpty()){
               ToastUtils.showShort(toastMessage)
          }
     }

     fun showProgress(){
          ProgressUtils.showProgress()
     }

     override fun onCleared() {
          super.onCleared()
          mLifecycle.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
     }


     override fun getLifecycle() = mLifecycle
}